<?php
/**
 * 验证码类
 */
class Code
{
	//配置
	public $config = [
		'width' => 200,
		'hieght'=>80,
		'length'=>4,
		'line' => 0,
		'font_size'=>40,
		'disturb'=>true,
		'bg'=>[255,255,255],
		'str'=>'zxcvbnmasdfghjklqwertyuiopASDFGHJKLZXCVBNMQWERTYUIOP1234567890'
	];

	public $src;

	public function __construct($config=[])
	{
		$this->config = array_merge($this->config,$config);
	}

	public function __get($name)
	{
		return $this->config[$name];
	}

	public function entry()
	{
		// 1 创建画面
		$this->_create();
		// 2 填充背景
		$this->_fill();
		// 3 画各种东西
		$this->_disturb();
		$this->_add_line();
		$this->_add_font();
		// 4 输出画面
		$this->_out();
	}

	protected function _create()
	{
		$this->src = imageCreateTrueColor($this->width,$this->hieght);
	}

	protected function _fill()
	{
		$color = imageColorAllocate($this->src,$this->bg[0],$this->bg[1],$this->bg[2]); 
		// 填充
		imageFill($this->src,0,0,$color);
	}

	public function _add_line()
	{
		for ($i=0; $i <$this->line ; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(50,255),mt_rand(50,255),mt_rand(50,255));

			imageline ($this->src, mt_rand(0,$this->width) , mt_rand(0,$this->hieght) , mt_rand(0,$this->width) ,mt_rand(0,$this->hieght), $color );
		}
	}

	public function _disturb()
	{
		if($this->disturb){
			for ($i=0; $i < 50; $i++) { 
				$color = imageColorAllocate($this->src,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
				$text = $this->str[mt_rand(0,strlen($this->str)-1)];
				imagettftext ( $this->src,10, mt_rand(-30,30) , mt_rand(0,$this->width) , mt_rand(0,$this->hieght), $color , COMMON_PATH.'/waterlily-script.woff.ttf', $text);
			}
		}
	}

	public function _add_font()
	{

		$str = '';

		for ($i=0; $i < $this->length; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(0,80),mt_rand(0,80),mt_rand(0,80));

			$text = $this->str[mt_rand(0,strlen($this->str)-1)];

			$str .=$text;

			$height = ($this->hieght+$this->font_size)/2;

			$witdh  = (($this->width/$this->length)-$this->font_size)/2+$i*($this->width/$this->length);

			imagettftext ( $this->src,$this->font_size, mt_rand(-15,15) , $witdh , $height, $color , COMMON_PATH.'/waterlily-script.woff.ttf', $text);

		}

		session_start();
		$_SESSION['code'] = $str;
	}

	protected function _out()
	{
		// var_dump($src);
		header("Content-type: image/png");
		// 输出画面
		imagepng($this->src);
	}
}
